package com.qq.server.dao;

import com.google.common.base.*;
import com.qq.common.User;
import com.qq.server.tools.DBUtil;
import com.qq.server.tools.IdGenerator;
import com.qq.server.tools.Md5;
import com.qq.server.tools.StringUtils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author weiBin
 * @date 2019/1/9
 */
public class UserDaoImpl implements UserDao {

    @Override
    public String insertUser(User user) {
        Connection conn = DBUtil.getConn();
        String sql = "insert into user (id,no,name,passwd) values(?,?,?,?)";
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            String id = IdGenerator.getUUID();
            statement.setString(1, id);
            statement.setString(2, user.getNo());
            statement.setString(3, user.getName());
            statement.setString(4, Md5.getMD5ofStr(user.getPasswd()));
            int i = statement.executeUpdate();
            if (i == 1) {
                return id;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
        return null;
    }

    @Override
    public boolean updateUser(User user) {
        Connection conn = DBUtil.getConn();
        StringBuffer sett = new StringBuffer();
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(user.getName())) {
            sett.append(" name = ?,");
            list.add(user.getName());
        }
        if (StringUtils.isNotEmpty(user.getPasswd())) {
            sett.append(" passwd = ?,");
            list.add(Md5.getMD5ofStr(user.getPasswd()));
        }
        if (StringUtils.isNotEmpty(user.getStatus())) {
            sett.append(" status = ?,");
            list.add(user.getStatus());
        }
        if (list.size() == 0) {
            return false;
        }
        String sql = String.format("update user set %s where id = ?", sett.toString().substring(0, sett.toString().length()));
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            for (int i = 0; i < list.size(); i++) {
                statement.setString(i + 1, list.get(i));
            }
            statement.setString(list.size() + 1, user.getId());
            int i = statement.executeUpdate();
            if (i == 1) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
        return false;
    }

    @Override
    public List<User> queryUserList(User user) {
        return queryUserList(user, 0);
    }

    private List<User> queryUserList(User user, int type) {
        List<User> list = new ArrayList<>();
        Connection conn = DBUtil.getConn();
        List<String> params = new ArrayList<>();
        List<String> values = new ArrayList<>();
        if (StringUtils.isNotEmpty(user.getId())) {
            params.add("id = ?");
            values.add(user.getId());
        }
        if (StringUtils.isNotEmpty(user.getNo())) {
            params.add("no = ?");
            values.add(user.getNo());
        }
        if (StringUtils.isNotEmpty(user.getName())) {
            params.add("name = ?");
            values.add(user.getName());
        }
        if (StringUtils.isNotEmpty(user.getStatus())) {
            params.add("status = ?");
            values.add(user.getStatus());
        }
        String str = "";
        if (params.size() == 0 && type == 1) {
            return null;
        } else if (params.size() > 0) {
            str = " and " + Joiner.on(" and ").join(params);
        }
        if (type == 1) {
            str += " limit 1";
        }
        String sql = String.format("select * from user where 1=1  %s", str);
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            for (int i = 0; i < values.size(); i++) {
                statement.setString(i + 1, values.get(i));
            }
            ResultSet rs = statement.executeQuery();
            readResult(list, rs);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
        return list;
    }

    private void readResult(List<User> list, ResultSet rs) throws SQLException {
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            try {
                Class<?> cls = Class.forName(User.class.getName());
                User o = (User) cls.newInstance();
                int columnCount = meta.getColumnCount();
                for (int j = 1; j <= columnCount; j++) {
                    String propertyName = StringUtils.formatStr(meta.getColumnLabel(j), "_");
                    try {
                        Field field = cls.getDeclaredField(propertyName);
                        field.setAccessible(true);
                        field.set(o, rs.getObject(j));
                    } catch (NoSuchFieldException ne) {
                        ne.getMessage();
                    }
                }
                list.add(o);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public User queryUserOne(User user) {
        List<User> list = queryUserList(user, 1);
        if (list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    public static void main(String[] args) {
        UserDaoImpl userDao = new UserDaoImpl();
        User user = new User();
        user.setName("张四");
        user.setPasswd("123456");
        user.setNo("593013911");
//        userDao.insertUser(user);
        List<User> userList = userDao.queryUserList(user);
        System.out.println(userList.get(0).getId());
        List<User> list = userDao.queryFriendList(userList.get(0).getId());
        System.out.println(list.size());
    }

    @Override
    public List<User> queryFriendList(String no) {
        List<User> list = new ArrayList<>();
        String sql = "select a.*,b.type from user a,friend b,user c where  a.id = b.to_User_Id and b.from_User_Id = c.id and  b.status = 1 and c.no = ?";
        Connection conn = DBUtil.getConn();
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1,no);
            ResultSet rs = statement.executeQuery();
            readResult(list,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(conn);
        }
        return list;
    }

}
